# -*- coding: utf-8 -*-
"""
多线程单例
实现线程安全需要配合锁的使用,只有占有锁的线程才能继续访问单例实例
"""

import threading

__all__ = ['Singleton']


# def singleton(cls):
#     instances = {}
#
#     def _singleton(*args, **kwargs):
#         if cls not in instances:
#             instances[cls] = cls(*args, **kwargs)
#         return instances[cls]
#
#     return _singleton


def synchronized(func):
    func.__lock__ = threading.Lock()

    def synced_func(*args, **kws):
        with func.__lock__:
            return func(*args, **kws)

    return synced_func


def Singleton(cls):
    instances = {}

    @synchronized
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return get_instance


# test
@Singleton
class test():
    a = 1


def worker():
    single_test = test()
    print("id----> %s" % id(single_test))

# if __name__ == "__main__":
#     task_list = []
#     for one in range(30):
#         t = threading.Thread(target=worker)
#         task_list.append(t)
#
#     for one in task_list:
#         one.start()
#
#     for one in task_list:
#         one.join()
